package com.zbiti.sentinel.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wangjin
 * @title: IndexController
 * @projectName sentinel
 * @description: TODO
 * @date 2022/5/30 0030 9:11
 */
@RestController

public class IndexController {
    private final static Logger log = LoggerFactory.getLogger(IndexController.class);
    /**
     * 初始化限流路由策略
     *
     * @return
     */
    @RequestMapping("/initFlowQpsRule")
    public String initFlowQpsRule() {
        List<FlowRule> rules = new ArrayList<FlowRule>();
        FlowRule rule1 = new FlowRule();
        // 创建限流资源
        rule1.setResource("getSentinelQps");
        // QPS控制在2以内
        rule1.setCount(2);
        // QPS限流
        rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
        //限流应用default
        rule1.setLimitApp("default");
        //添加该限流规则
        rules.add(rule1);
        FlowRuleManager.loadRules(rules);
        return "....限流配置初始化成功..";
    }
    /**
     * 演示getSentinelQps QPS 对接口限流
     *
     * @return
     */
    @RequestMapping("/getSentinelQps")
    public String getSentinelQps() {
        Entry entry = null;
        try {
            entry = SphU.entry("getSentinelQps");
            // 执行我们服务需要保护的业务逻辑
            log.info("正常执行业务逻辑代码...");
            log.debug("正常执行业务逻辑代码...");
            return "getSentinelQps";
        } catch (Exception e) {
            log.error("<e:{}>", e);
            return "该接口访问频率过多，请稍后重试!";
        } finally {
            // SphU.entry(xxx) 需要与 entry.exit() 成对出现,否则会导致调用链记录异常
            if (entry != null) {
                entry.exit();
            }
        }
    }
    /**
     * @Author wangjin
     * @Description //初始化限流路由策略
     * @Date 2022/5/30 0030
     * @Param []
     * @return java.lang.String
     **/
    @RequestMapping("/initFlowQpsRule2")
    public String initFlowQpsRule2(){
        List<FlowRule> rules=new ArrayList<FlowRule>();
        FlowRule rule1=new FlowRule();
        //创建
        return  "";

    }

}
